from typing import Any, List, Optional

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.api import deps
from app.models.user import User
from app.schemas.risk_issue import (
    RiskCreate, RiskUpdate, RiskResponse,
    RiskCommentCreate, RiskCommentResponse,
    IssueCreate, IssueUpdate, IssueResponse,
    IssueCommentCreate, IssueCommentResponse
)
from app.services import risk_issue as risk_issue_service


router = APIRouter()


# 风险相关路由
@router.get("/risks", response_model=List[RiskResponse])
async def read_risks(
    db: AsyncSession = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
    project_id: Optional[int] = None,
    status: Optional[str] = None,
    severity: Optional[str] = None,
    assignee_id: Optional[int] = None,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """获取风险列表，可按项目、状态、严重程度和负责人筛选"""
    risks = await risk_issue_service.get_risks(
        db=db, skip=skip, limit=limit,
        project_id=project_id, status=status,
        severity=severity, assignee_id=assignee_id
    )
    return risks


@router.post("/risks", response_model=RiskResponse, status_code=status.HTTP_201_CREATED)
async def create_risk(
    *,
    db: AsyncSession = Depends(deps.get_db),
    risk_in: RiskCreate,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """创建风险"""
    risk = await risk_issue_service.create_risk(
        db=db, obj_in=risk_in, creator_id=current_user.id
    )
    return risk


@router.get("/risks/{risk_id}", response_model=RiskResponse)
async def read_risk(
    *,
    db: AsyncSession = Depends(deps.get_db),
    risk_id: int,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """获取特定风险详情"""
    risk = await risk_issue_service.get_risk_by_id(db=db, id=risk_id)
    if not risk:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Risk not found",
        )
    return risk


@router.put("/risks/{risk_id}", response_model=RiskResponse)
async def update_risk(
    *,
    db: AsyncSession = Depends(deps.get_db),
    risk_id: int,
    risk_in: RiskUpdate,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """更新风险"""
    risk = await risk_issue_service.get_risk_by_id(db=db, id=risk_id)
    if not risk:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Risk not found",
        )
    # 检查权限：只有风险负责人、创建者或超级用户可以更新风险
    if risk.assignee_id != current_user.id and risk.creator_id != current_user.id and not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Not enough permissions",
        )
    risk = await risk_issue_service.update_risk(db=db, db_obj=risk, obj_in=risk_in)
    return risk


@router.delete("/risks/{risk_id}", response_model=RiskResponse)
async def delete_risk(
    *,
    db: AsyncSession = Depends(deps.get_db),
    risk_id: int,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """删除风险"""
    risk = await risk_issue_service.get_risk_by_id(db=db, id=risk_id)
    if not risk:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Risk not found",
        )
    # 检查权限：只有风险创建者或超级用户可以删除风险
    if risk.creator_id != current_user.id and not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Not enough permissions",
        )
    risk = await risk_issue_service.delete_risk(db=db, id=risk_id)
    return risk


@router.get("/risks/{risk_id}/comments", response_model=List[RiskCommentResponse])
async def read_risk_comments(
    *,
    db: AsyncSession = Depends(deps.get_db),
    risk_id: int,
    skip: int = 0,
    limit: int = 100,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """获取风险评论列表"""
    risk = await risk_issue_service.get_risk_by_id(db=db, id=risk_id)
    if not risk:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Risk not found",
        )
    comments = await risk_issue_service.get_risk_comments(
        db=db, risk_id=risk_id, skip=skip, limit=limit
    )
    return comments


@router.post("/risks/{risk_id}/comments", response_model=RiskCommentResponse, status_code=status.HTTP_201_CREATED)
async def create_risk_comment(
    *,
    db: AsyncSession = Depends(deps.get_db),
    risk_id: int,
    comment_in: RiskCommentCreate,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """创建风险评论"""
    risk = await risk_issue_service.get_risk_by_id(db=db, id=risk_id)
    if not risk:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Risk not found",
        )
    # 确保评论关联到正确的风险
    if comment_in.risk_id != risk_id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Comment must be associated with the specified risk",
        )
    comment = await risk_issue_service.create_risk_comment(
        db=db, obj_in=comment_in, creator_id=current_user.id
    )
    return comment


# 问题相关路由
@router.get("/issues", response_model=List[IssueResponse])
async def read_issues(
    db: AsyncSession = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
    project_id: Optional[int] = None,
    status: Optional[str] = None,
    priority: Optional[str] = None,
    assignee_id: Optional[int] = None,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """获取问题列表，可按项目、状态、优先级和负责人筛选"""
    issues = await risk_issue_service.get_issues(
        db=db, skip=skip, limit=limit,
        project_id=project_id, status=status,
        priority=priority, assignee_id=assignee_id
    )
    return issues


@router.post("/issues", response_model=IssueResponse, status_code=status.HTTP_201_CREATED)
async def create_issue(
    *,
    db: AsyncSession = Depends(deps.get_db),
    issue_in: IssueCreate,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """创建问题"""
    issue = await risk_issue_service.create_issue(
        db=db, obj_in=issue_in, creator_id=current_user.id
    )
    return issue


@router.get("/issues/{issue_id}", response_model=IssueResponse)
async def read_issue(
    *,
    db: AsyncSession = Depends(deps.get_db),
    issue_id: int,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """获取特定问题详情"""
    issue = await risk_issue_service.get_issue_by_id(db=db, id=issue_id)
    if not issue:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Issue not found",
        )
    return issue


@router.put("/issues/{issue_id}", response_model=IssueResponse)
async def update_issue(
    *,
    db: AsyncSession = Depends(deps.get_db),
    issue_id: int,
    issue_in: IssueUpdate,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """更新问题"""
    issue = await risk_issue_service.get_issue_by_id(db=db, id=issue_id)
    if not issue:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Issue not found",
        )
    # 检查权限：只有问题负责人、创建者或超级用户可以更新问题
    if issue.assignee_id != current_user.id and issue.creator_id != current_user.id and not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Not enough permissions",
        )
    issue = await risk_issue_service.update_issue(db=db, db_obj=issue, obj_in=issue_in)
    return issue


@router.delete("/issues/{issue_id}", response_model=IssueResponse)
async def delete_issue(
    *,
    db: AsyncSession = Depends(deps.get_db),
    issue_id: int,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """删除问题"""
    issue = await risk_issue_service.get_issue_by_id(db=db, id=issue_id)
    if not issue:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Issue not found",
        )
    # 检查权限：只有问题创建者或超级用户可以删除问题
    if issue.creator_id != current_user.id and not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Not enough permissions",
        )
    issue = await risk_issue_service.delete_issue(db=db, id=issue_id)
    return issue


@router.get("/issues/{issue_id}/comments", response_model=List[IssueCommentResponse])
async def read_issue_comments(
    *,
    db: AsyncSession = Depends(deps.get_db),
    issue_id: int,
    skip: int = 0,
    limit: int = 100,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """获取问题评论列表"""
    issue = await risk_issue_service.get_issue_by_id(db=db, id=issue_id)
    if not issue:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Issue not found",
        )
    comments = await risk_issue_service.get_issue_comments(
        db=db, issue_id=issue_id, skip=skip, limit=limit
    )
    return comments


@router.post("/issues/{issue_id}/comments", response_model=IssueCommentResponse, status_code=status.HTTP_201_CREATED)
async def create_issue_comment(
    *,
    db: AsyncSession = Depends(deps.get_db),
    issue_id: int,
    comment_in: IssueCommentCreate,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """创建问题评论"""
    issue = await risk_issue_service.get_issue_by_id(db=db, id=issue_id)
    if not issue:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Issue not found",
        )
    # 确保评论关联到正确的问题
    if comment_in.issue_id != issue_id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Comment must be associated with the specified issue",
        )
    comment = await risk_issue_service.create_issue_comment(
        db=db, obj_in=comment_in, creator_id=current_user.id
    )
    return comment